package cmbchina;

import com.jcraft.jsch.JSchException;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.Task;
import org.flowable.engine.*;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.flowable.engine.form.FormProperty;
import org.flowable.engine.form.TaskFormData;
import org.flowable.form.api.*;
import org.flowable.form.api.FormService;
import org.flowable.form.model.FormField;
import org.flowable.form.model.FormModel;
import org.flowable.task.api.*;
import org.flowable.variable.api.persistence.entity.VariableInstance;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by zm on 17-7-13.
 */
public class MyFlowableServiceTest implements JavaDelegate {


    @Override
    public void execute(DelegateExecution execution) {
        System.out.println("=====================开始调用SA==============");

        System.out.println("=====================getCurrentActivityId=============="+execution.getCurrentActivityId());
        System.out.println("=====================getEventName=============="+execution.getEventName());
        System.out.println("=====================getParentId=============="+execution.getParentId());
        System.out.println("=====================getTenantId=============="+execution.getTenantId());
        System.out.println("=====================getCurrentActivityId=============="+execution.getCurrentActivityId());
        System.out.println("=====================getProcessDefinitionId=============="+execution.getProcessDefinitionId());
        System.out.println("=====================getProcessInstanceBusinessKey=============="+execution.getProcessInstanceBusinessKey());
        System.out.println("=====================getRootProcessInstanceId=============="+execution.getRootProcessInstanceId());
        Map<String,Object> parentMap = execution.getVariables();
        System.out.println("=====================上一步的参数==============");
//        for (String key : parentMap.keySet()) {
//            System.out.println("key= "+ key + " and value= " + parentMap.get(key));
//        }
        System.out.println("=====================所有的参数==============");
        Map<String,Object> map= execution.getTransientVariables();

        for (String key : map.keySet()) {
            System.out.println("key= "+ key + " and value= " + map.get(key));
        }
        Map<String, VariableInstance> testmap= execution.getVariableInstances();
        for (String key : testmap.keySet()) {
            System.out.println("key11= "+ key + " and value222= " + testmap.get(key));
        }
        System.out.println("=====================节点信息==============");
        List<DelegateExecution> exs = (List<DelegateExecution>) execution.getExecutions();
//        execution.getParent().getCurrentFlowElement();
//        for (DelegateExecution ex : exs) {
            System.out.println("=====================execution.getParent().getCurrentActivityId()============="+execution.getParent().getCurrentActivityId());
            FlowElement fe= execution.getCurrentFlowElement();
            System.out.println("=====================flowelementClass=============="+fe.getClass());
            System.out.println("=====================fe.getName()+fe.getId()=============="+fe.getName()+fe.getId());
//            if (fe instanceof UserTask) {
//                UserTask u = (UserTask) fe;
//                List<org.flowable.bpmn.model.FormProperty> form = fe.get();
//                for(org.flowable.bpmn.model.FormProperty fo:form){
//                    System.out.println("=====================formId===name==========="+fo.getId()+ "--->>>>"
//                            + fo.getName());
//                }
//                List outgoingFlows = u.getOutgoingFlows();
//                System.err.println("outgoingFlows:" + outgoingFlows);
//            }


//        }

        System.out.println("=====================formId===filds===========--->>>>");
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        RuntimeService runtimeService = processEngine.getRuntimeService();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        TaskService taskService = processEngine.getTaskService();


        ManagementService managementService = processEngine.getManagementService();
        IdentityService identityService = processEngine.getIdentityService();
        HistoryService historyService = processEngine.getHistoryService();
        DynamicBpmnService dynamicBpmnService = processEngine.getDynamicBpmnService();
        List<org.flowable.task.api.Task> tasks = taskService.createTaskQuery().processInstanceId(execution.getProcessInstanceId()).list();
        String command = "/home/ggroot/oracle/cmb_ora_restore.sh -h rtishdb03 -d dbtest -c test -t 06/27/2017 -s 11:35:06 -type dir -dir /u01/backup";
        if(parentMap.containsKey("scriptName")){
            command = parentMap.get("scriptName").toString();
        }
        for(org.flowable.task.api.Task task:tasks){
            System.out.println("=====================taskid===name===========--->>>>"+task.getId()+"=="+task.getName()+"task.getFormKey()"+task.getFormKey());

//            FormModel fm= formService.getFormInstanceModelByKey(task.getFormKey(),task.getId(),null)
            FormModel fm = taskService.getTaskFormModel(task.getId());
            Map<String, Object> parentParms= task.getProcessVariables();
            for (FormField fild : fm.getFields()) {
                if(!"scriptName".equals(fild.getId())){
//                    System.out.println("=====================key===value===========--->>>>"+task.getId()+"=="+task.getName());
                    command = command + " -"+fild.getId() +" "+(fild.getValue()==null?"":fild.getValue());
                }
            }
        }
        System.out.println("command=="+command);

//        BpmnModel bpmnModel = repositoryService.getBpmnModel(execution.getProcessDefinitionId());
//        Process process = bpmnModel.getProcesses().get(0);
//        Collection<FlowElement> flowElements = process.getFlowElements();
//        for (FlowElement flowElement : flowElements) {
//            if (flowElement instanceof UserTask) {
//                UserTask u = (UserTask) flowElement;
//                List outgoingFlows = u.getOutgoingFlows();
//                System.err.println("outgoingFlows:" + outgoingFlows);
//            }
//            System.err.println(flowElement.getId() + "--->>>>"
//                    + flowElement.getName());
//
//        }
        JschUtil jschUtil = new JschUtil();
        boolean isConnected = false;
        try {
            try {
                isConnected  = jschUtil.connect();
            } catch (JSchException e) {
                e.printStackTrace();
            }

            if(isConnected == true){
                try {
                    int returnCode =  jschUtil.execCmdReturnCode(command);
                    System.out.println("返回码" +returnCode);
                    execution.setVariable("returnCode", returnCode);
                } catch (Exception e) {
                    execution.setVariable("returnCode", 1);
                    e.printStackTrace();
                }
                jschUtil.getResultList();
                StringBuffer sb =new StringBuffer("");
                for(String rs:jschUtil.getResultList()) {
                    sb.append(rs);
//                    System.out.println(rs);

                }
                jschUtil.close();
//                execution.setVariable(execution.getCurrentActivityId()+"-result", jschUtil.execCmdReturnCode(command));
            }
            else{
                execution.setVariable("returnCode", 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
            execution.setVariable("returnCode", 1);
        }
        System.out.println("==========================end====================================");

    }


}
